/*@@

    Copyright (c) 2010 BlueSky LTD.  All rights reserved. 

    Created_datetime : 2010-6-23 16:48:14

    File Name :	base_thread.cpp

    Author : Wang Hu (ghoststears@gmail.com)

    Description : 

@@*/


#include <cstdio>
#include "base/base_thread.h"


namespace BLK
{
    threadfunc_t STDPREFIX Thread::ThrFunc(threadparam_t param)
    {
        Thread* pThr = (Thread*)param;
        if (pThr->IsRuning())
        {
            pThr->Action();
        }

        END_THREAD;

        return 0;
    }

    Thread::Thread()
    : m_runing(false)
    {

    }

    Thread::~Thread()
    {
        if (IsRuning()) 
        {
            CLOSE_THREAD(m_thread);
        }
    }

    int Thread::Start()
    {
        if (IsRuning())
        {
            return 0;
        }
        
        m_runing = true;

#ifdef _WIN32
        m_thread = (HANDLE)_beginthreadex(NULL, 0, &ThrFunc, this, 0, NULL);
#else
        pthread_attr_t attr;

        pthread_attr_init(&attr);
        pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
        if (pthread_create(&m_thread,&attr, ThrFunc, this) == -1)
        {
            perror("Thread: create failed");
        
            m_runing = false;

            return -1;
        }
#endif

        return 0;
    }

    int Thread::Stop()
    {
        if (IsRuning()) 
        {
            CLOSE_THREAD(m_thread);

            m_runing = false;

            return 0;
        }

        return -1;
    }

    bool Thread::IsRuning() const
    {
        return m_runing;
    }

    pthread_t Thread::GetThread() const
    {
        return m_thread; 
    }
};
